'RKD nmspc: 20120610 :: Imports EntertainmentManager
Imports BusinessLogicLayer.BLMain
Imports DataAccessLayer
Imports UniversalLayer.ULMain
Imports Microsoft.VisualBasic.Logging
Imports System.IO

Public NotInheritable Class BLException
    Inherits Exception

    ''' <summary>
    ''' Exception instance
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared oException As Exception
    ''' <summary>
    ''' Method name that raised the error
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared sExceptionSource As String
    ''' <summary>
    ''' Method name which initiated the process causing the error
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared sInitiatorMethod As String
    ''' <summary>
    ''' File details of exception source
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared sFileDetails As String
    ''' <summary>
    ''' Personal Notes and Comments
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared sNotesComments As String
    ''' <summary>
    ''' TRUE: Display error to user
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared bDisplayErrorMessage As Boolean
    ''' <summary>
    ''' DataTable containing all settings
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared dtSettingsMain As DataTable

    '' ''Public Sub New(ByVal ex As Exception, ByVal sCallerMethod As String)
    '' ''    ThrowBLException(ex, sCallerMethod)
    '' ''
    '' ''    ''All_Exception()
    '' ''    ''MessageBox.Show("Error: " & ex.Message & vbCrLf & vbCrLf & "Details:" & vbCrLf & ex.ToString, "Error: GUIPopulator.SearchByView", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '' ''
    '' ''    ''SqlClient.SqlException()
    '' ''    ''Dim errMessage As String = "SQL Server error :: " & exSQL.ErrorCode & " : " & exSQL.Message & vbCrLf & vbCrLf & "Details:" & vbCrLf & exSQL.ToString
    '' ''    ''MessageBox.Show(errMessage, "SQL error: GUIPopulator.SearchByView", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '' ''    ''errMessage = Nothing
    '' ''
    '' ''    ''Dim frmExceptionViewer As EntertainmentManager.frmExceptionViewer
    '' ''    ''frmExceptionViewer = New EntertainmentManager.frmExceptionViewer(ex, "EntertainmentManager.GUIPopulator.InitializeFormMain")
    '' ''    ''frmExceptionViewer.ShowDialog(myFormMain)
    '' ''    ''frmExceptionViewer.Close()
    '' ''    ''frmExceptionViewer.Dispose()
    '' ''End Sub

    ''' <summary>
    ''' Displays error message, logs error into DB and LOG file
    ''' </summary>
    ''' <param name="ex">Exception</param>
    ''' <param name="sInitiatorMethodName">Initiator Method Name</param>
    ''' <param name="bDisplayError">TRUE: Display error to user</param>
    ''' <remarks></remarks>
    Public Shared Sub ThrowBLException(ByVal ex As Exception, ByVal sInitiatorMethodName As String, Optional ByVal bDisplayError As Boolean = True)
        Dim _StackFrame As StackFrame
        Try
            _StackFrame = New StackFrame(1, True)
            sInitiatorMethodName = Nothing
            sInitiatorMethodName = _StackFrame.GetMethod.ReflectedType.FullName & "." & Replace(_StackFrame.GetMethod.Name, ".ctor", "New")
            sFileDetails = "File: " & _StackFrame.GetFileName & vbCrLf & "Line: " & CStr(_StackFrame.GetFileLineNumber)
        Finally
            _StackFrame = Nothing
        End Try

        oException = ex
        sInitiatorMethod = sInitiatorMethodName
        sExceptionSource = ex.TargetSite.ReflectedType.FullName & "." & ex.TargetSite.Name
        bDisplayErrorMessage = bDisplayError
        Dim _DLSettings As DataAccessLayer.DLSettings
        Try
            _DLSettings = New DataAccessLayer.DLSettings
            dtSettingsMain = _DLSettings.FetchAllSettings 'CType(_DLSettings.FetchSettings("", "", "", DataAccessLayer.DLSettings.eSettingsReturnType.DataTable), DataTable)
        Finally
            _DLSettings = Nothing
        End Try

        'RKD: PENDING_20120524: Take_snapshot_of_error_programmatically()
        If bDisplayErrorMessage Then _
            sNotesComments = InputBox("Please input your Notes and Comments.." & vbCrLf & "(1000 characters allowed)", "Notes and Comments", sInitiatorMethod)
        If CBool(DLSettings.FetchOneSetting(dtSettingsMain, "ErrorLog", "FileLog")) Then LogToFile()
        If CBool(DLSettings.FetchOneSetting(dtSettingsMain, "ErrorLog", "DBLog")) Then LogToDB()
        If CBool(DLSettings.FetchOneSetting(dtSettingsMain, "ErrorLog", "Display")) And bDisplayErrorMessage Then DisplayErrorMessage()
    End Sub

    ''' <summary>
    ''' Displays error message
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared Sub DisplayErrorMessage()
        ''Select Case MsgBox(oException.Message & vbCrLf & vbCrLf & oException.ToString & vbCrLf & vbCrLf & "Do you want to copy the error details to Clipboard ??", MsgBoxStyle.YesNo, "BLException_ERROR: " & sInitiatorMethod)
        ''    Case MsgBoxResult.Yes : My.Computer.Clipboard.SetText(oException.Message & vbCrLf & vbCrLf & oException.ToString)
        ''    Case MsgBoxResult.No 'Do Nothing
        ''End Select

        'RKD : 20120610 :: Dim frmExceptionViewer As EntertainmentManager.frmErrorViewer
        Try
            'RKD : 20120610 :: frmExceptionViewer = New EntertainmentManager.frmErrorViewer(oException, sInitiatorMethod, sExceptionSource, sFileDetails)
            'RKD : 20120610 :: frmExceptionViewer.ShowDialog()
            'RKD : 20120610 :: frmExceptionViewer.Dispose()
        Finally
            'RKD : 20120610 :: frmExceptionViewer = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Logs error into DB
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared Sub LogToDB()
        'RKD: PENDING_20120524: fix_IO_exception()

        Dim _DLWriter As DataAccessLayer.DLWriter
        Try
            _DLWriter = New DataAccessLayer.DLWriter("BLMain")
            _DLWriter.LogErrorToDB(oException, sInitiatorMethod, sExceptionSource, sNotesComments)
        Finally
            _DLWriter = Nothing
        End Try
    End Sub

    ''' <summary>
    ''' Logs error into *.log file
    ''' </summary>
    ''' <remarks></remarks>
    Private Shared Sub LogToFile()
        Dim sAppPath As String
        Dim tAppLaunchTime As DateTime
        'dim sLogPath as String=Configuration.ConfigurationSettings.AppSettings(
        Dim sLogPath As String
        Dim sLogFile As String
        Dim oLogger As FileLogTraceListener
        Dim strLogMessage As Text.StringBuilder
        Dim wr As StreamWriter

        ''Dim _FilesStream As FileStream
        ''Try
        ''    _FilesStream = New FileStream(sFileName, IO.FileMode.Open)
        ''Catch ex As Exception
        ''    _FilesStream.Close()
        ''Finally
        ''    _FilesStream.Close()
        ''    _FilesStream = Nothing
        ''End Try

        Try
            'RKD : 20120610 :: sAppPath = frmEntertainmentManager.sApplicationPath
            'RKD : 20120610 :: tAppLaunchTime = frmEntertainmentManager.tAppLaunchTime
            sLogPath = sAppPath & "\Logs\" & Format(tAppLaunchTime, "yyyy-MM-dd")
            sLogFile = "ErrorLog_" & Format(tAppLaunchTime, "HHmmss") '& "_" & sMethodName '& ".log"
            oLogger = New FileLogTraceListener
            oLogger.Append = True
            oLogger.CustomLocation = sLogPath
            oLogger.BaseFileName = sLogFile
            sLogFile = oLogger.FullLogFileName

            If Not IsDirectoryExists(sLogPath) Then Directory.CreateDirectory(sLogPath)
            If Not IsFileExists(sLogFile) Then File.Create(sLogFile)

            If IsFileExists(sLogFile) Then
                strLogMessage = New Text.StringBuilder
                wr = New StreamWriter(sLogFile, True, System.Text.Encoding.Default)

                strLogMessage.AppendLine("Error :: " & oException.Message)
                strLogMessage.AppendLine("Initiator Method :: " & sInitiatorMethod)
                strLogMessage.AppendLine("Error Source :: " & sExceptionSource)
                strLogMessage.AppendLine("Log time :: " & Format(Now, "")).AppendLine()
                strLogMessage.AppendLine(oException.StackTrace)
                strLogMessage.AppendLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=").AppendLine()

                wr.WriteLine(strLogMessage.ToString)
                wr.Flush()
                wr.Close()
            End If

            '' ''oLogger.WriteException(ex, TraceEventType.Error, sMethodName)
            '' ''oLogger.WriteEntry(ex.Message, TraceEventType.Error)

        Finally
            sAppPath = Nothing
            tAppLaunchTime = Nothing
            sLogPath = Nothing
            sLogFile = Nothing
            oLogger = Nothing
            strLogMessage = Nothing
            wr = Nothing
        End Try


        '' //string strErrorFilePath = string.Empty;
        '' //strErrorFilePath = ConfigurationSettings.AppSettings["ErrorFilePath"];
        '' //System.IO.StreamWriter swErrorLogger = new System.IO.StreamWriter(strErrorFilePath);
        '' //StringBuilder strErrorMessage = new StringBuilder();
        '' //strErrorMessage.Append(ex.StackTrace.ToString());
        '' //strErrorMessage.Append("\n");
        '' //strErrorMessage.Append(System.DateTime.Now);
        '' //swErrorLogger.Write(strErrorMessage);
        '' //swErrorLogger.Flush();
        '' //swErrorLogger.Close();
    End Sub
End Class
